package main

import (
	"bufio"
	"io"
	"log"
	"net"
)

func server() {
	listen, err := net.Listen("tcp4", ":18080")
	if err != nil {
		log.Fatal("listen port error")
	}
	defer listen.Close()

	for {
		conn, err := listen.Accept()
		if err != nil {
			log.Println(err)
			continue
		}

		go handler(conn)
	}
}

func handler(conn net.Conn) {
	defer conn.Close()
	buf := make([]byte, 1024)
	r := bufio.NewReader(conn)
	w := bufio.NewWriter(conn)

ILOOP:
	for {
		n, err := r.Read(buf)
		data := string(buf[:n])
		switch err {
		case io.EOF:
			break ILOOP
		case nil:
			log.Println("Receive:", data)
			if n == 0 {
				break
			}
		default:
			log.Fatalln("Receive data error", err)
		}
	}
	w.Write([]byte("Pong"))
	w.Flush()
}

func main() {
	server()
}
